package fr.vahren.sriksal.controller.impl;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fr.vahren.sriksal.business.IAuthBusiness;
import fr.vahren.sriksal.business.exception.InternalErrorException;
import fr.vahren.sriksal.business.exception.UserAlreadyUsedException;
import fr.vahren.sriksal.controller.IAuthController;
import fr.vahren.sriksal.controller.bean.UserInfo;

public class AuthController  extends ActionSupport implements IAuthController{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9193817281975230307L;

	private IAuthBusiness authBusiness;
	
	private UserInfo user;

	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.controller.impl.IAuthController#getUser()
	 */
	@Override
	public UserInfo getUser() {
		return user;
	}


	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.controller.impl.IAuthController#setUser(fr.vahren.sriksal.controller.bean.UserInfo)
	 */
	@Override
	public void setUser(UserInfo user) {
		this.user = user;
	}


	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.controller.impl.IAuthController#setAuthBusiness(fr.vahren.sriksal.business.IAuthBusiness)
	 */
	@Override
	public void setAuthBusiness(IAuthBusiness authBusiness) {
		this.authBusiness = authBusiness;
	}
	
	
	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.controller.impl.IAuthController#checkUser()
	 */
	@Override
	public String checkUser(){
		boolean res = false;
		try {
			res = authBusiness.checkPassword(user.getLogin(), user.getPassword());
		} catch (InternalErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(res){
			Map<String, Object> session = ActionContext.getContext().getSession();
			session.put("user", user);
			return SUCCESS;
		}else{
			return ERROR;
		}
	}
	
	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.controller.impl.IAuthController#createUser()
	 */
	@Override
	public String createUser(){
		try {
			authBusiness.createUser(user.getLogin(), user.getPassword());
			Map<String, Object> session = ActionContext.getContext().getSession();
			session.put("user", user);
		} catch (UserAlreadyUsedException e) {
			return ERROR;
		} catch (InternalErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.controller.impl.IAuthController#execute()
	 */
	@Override
	public String execute() throws Exception {
		return super.execute();
	}


	@Override
	public String logoutUser() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if(session.containsKey("user")){
			session.remove("user");
			return SUCCESS;
		}else{
			// user not logged in!
			return ERROR;
		}
	}

}
